package club.ruanx.movie.aop.aspect;

import club.ruanx.acl.service.SysParamService;
import club.ruanx.acl.service.exception.SysRedisException;
import club.ruanx.exception.BaseException;
import club.ruanx.movie.common.aop.annotation.FilterSensitiveCommentWords;
import club.ruanx.movie.common.constraint.MovieParamConstraint;
import club.ruanx.util.AspectUtils;
import club.ruanx.util.BadWordUtil;
import club.ruanx.util.SpelUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.util.HashSet;

/**
 * @author 阮胜
 * @date 2019/2/16 16:37
 */
@Component
@Aspect
@Slf4j
public class CommentAspect {

    public CommentAspect(SysParamService sysParamService) {
        try {
            String sensitiveWords = sysParamService.findTop1ByFlag(MovieParamConstraint.MOVIE_COMMENT_SENSITIVE_WORD).getValue();
            BadWordUtil.words = new HashSet<>(JSON.parseArray(sensitiveWords, String.class));
        } catch (SysRedisException e) {
            log.error("加载评论敏感词汇列表失败");
        }

    }

    @Before("@annotation(filterSensitiveCommentWords)")
    public void intercept(JoinPoint joinPoint, FilterSensitiveCommentWords filterSensitiveCommentWords) throws BaseException {
        String[] methodParamNames = AspectUtils.getMethodParamNames(joinPoint);
        String content = SpelUtils.parseExpression(filterSensitiveCommentWords.key(), methodParamNames, joinPoint.getArgs());
        if (BadWordUtil.isContaintBadWord(content, BadWordUtil.MIN_MATCH_TYPE)) {
            throw new BaseException("评论中含有非法词汇");
        }
    }
}
